<template>
  <div class="EmergencyList">
    <div class="flex location-wrap">
      <span class="white">当前位置：</span>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/TrainingPlan' }">培训演练</el-breadcrumb-item>
        <el-breadcrumb-item>培训计划</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="box">
      <!-- 列表筛选 -->
      <filterTitle @query="query" @reset="reset" :form="form" labelWidth="140px" :formData="formData"
        @node-click="deptChoose">
        <!-- <el-form slot="filter" class="form" ref="form" :model="form" inline size="small" label-width="140px">
          <el-form-item :label="item.label + '：'" v-for="(item, index) in formData" :key="index" :rules="rules[item.id]" :prop="item.id">
            <LsdForm :compData="item" :form="form" @node-click="deptChoose(arguments, item)" @change="selectChange(arguments, item)" />
          </el-form-item>
        </el-form> -->
      </filterTitle>
      <!-- 列表表格 -->
      <LsdTable slot="yjrwlb" :paginationAtrrs="table.paginationAtrrs" @pageChange="handleSizeChange"
        :compRef="table.compRef" ref="yjrwlb" :columns="table.columns" :title="table.title" :actions="table.actions"
        :tableData="table.tableData" :tableAttr="table.tableAttr" :isShowPage="table.isShowPage"
        :isSelectFlag="table.isSelectFlag" :isSequenceFlag="table.isSequenceFlag" @onActionClick="onActionClick" />
    </div>
    <LsdDialog :dialogConfig="dialogConfig" @handleBtn="handleBtn" @close="close">
      <LsdDialogTitle slot="dialog" :titleConfig="titleConfig" :activeNames="activeNames">
        <div slot="slot1" class="uploadBox">
          <LsdTable slot="slot1" :compRef="yearsImportConfig.table.compRef" ref="yjrwlb"
            :columns="yearsImportConfig.table.columns" :tableData="yearsImportConfig.table.tableData"
            :tableAttr="yearsImportConfig.table.tableAttr" :isSelectFlag="yearsImportConfig.table.isSelectFlag"
            :isSequenceFlag="yearsImportConfig.table.isSequenceFlag" />
          <DialogForm ref="formComponent" @handleBeforeUpload="((file) => { handleBeforeUpload(file, 1); })"
            :formConfig="yearsImportConfig.formConfig">
            <div slot="upload" class="upload">
              <div class="upload" @click.prevent.stop="noPrevent">
                <el-input class="sjgy" v-model="fileListName" :disabled="true"></el-input>
              </div>
              <el-button slot="trigger" type="primary">导入</el-button>
              <el-button slot="trigger" @click.stop="onExport">下载模板</el-button>
              <el-button @click.stop="clear(1)">清除</el-button>
            </div>
          </DialogForm>
          <DialogForm ref="formComponent2" @handleBeforeUpload="((file) => { handleBeforeUploads(file, 2); })"
            :formConfig="yearsImportConfig.formConfig2">
            <div slot="upload1" class="upload">
              <div class="upload" @click.prevent.stop="noPrevent">
                <el-input class="sjgy" v-model="fileListName1" :disabled="true"></el-input>
              </div>
              <el-button type="primary">导入</el-button>
              <el-button @click.stop="clear(2)">清除</el-button>
            </div>
          </DialogForm>
        </div>
        <DialogForm ref="formComponent1" slot="slot2" :formConfig="yearsImportConfig.formConfig1" />
      </LsdDialogTitle>
    </LsdDialog>
  </div>
</template>

<script>
import { trainingYearlyListPage, trainingYearlyUpload, trainingYearlyExcelDetail, trainingYearlyDetail, trainingYearDowmload } from "@/api/TrainingAndExercise/ndpxjh.js";
import { formData } from "./config/Annualplan";
import { getUnitTreeApi } from "@/api/EarlyWarningManagement/yjrb";
import { UploadFile, loadFile } from "@/api/common.js";
import { showTime } from "@/lib";
import common from "@/utils/common.js";
export default {
  data() {
    return {
      formData: formData,
      table: {
        isSelectFlag: false,
        compRef: "yjrwlb",
        isSequenceFlag: true,
        isShowPage: true,
        resetFlag: true,
        loading: false,
        title: "年度培训计划列表",
        actions: [
          {
            id: "YearlyUpload",
            text: "导入",
            type: "primary",
            btnAttr: { size: "small" }
          }
          // {
          //   id: "add",
          //   text: "新增",
          //   btnAttr: { size: "small" }
          // }
        ],
        tableData: [],
        columns: [
          {
            prop: "trainingProjectName",
            label: "培训项目",
            align: "left",
            "min-width": "160px"
            // render: (h, { row }) => {
            //   return (<div>
            //     {<span style='color:#3561fd;cursor:pointer;text-decoration: underline;' {...{
            //       on: {
            //         click: () => {
            //           this.toTaskDetail(row.id);
            //         }
            //       }
            //     }}>
            //       {row.trainingProjectName}
            //     </span>}
            //   </div>);
            // }
          },
          {
            prop: "organisedUnitName",
            label: "主办单位",
            align: "center",
            "min-width": "130px"
          },
          {
            prop: "trainingContent",
            label: "培训内容",
            align: "left",
            "min-width": "290px"
          },
          {
            prop: "trainingTarget",
            label: "培训对象",
            align: "cenleftter"
          },
          {
            prop: "projectType",
            label: "计划类型",
            align: "center",
            formatter: (row, column, cellValue, index) => {
              if (cellValue === 1) {
                return "年度";
              } else if (cellValue === 2) {
                return "月度";
              } else if (cellValue === 3) {
                return "临时";
              }
            }
          },
          {
            prop: "trainingPeriod",
            label: "培训总期次",
            align: "center",
            formatter: (row, column, cellValue, index) => {
              if (cellValue !== null) {
                return `${cellValue}期`;
              }
            }
          },
          {
            prop: "planCompleteTime",
            label: "计划完成时间",
            align: "center",
            "min-width": "120px"
          },
          {
            prop: "trainingYearly",
            label: "培训年度",
            align: "center"
          },
          {
            prop: "attachInfo",
            label: "附件",
            align: "center",
            "min-width": "80px",
            render: (h, { row }) => {
              return (<div>
                {<span style='color:#3561fd;cursor:pointer;text-decoration: underline;' {...{
                  on: {
                    click: () => {

                      this.toTaskDetails(row.id);
                    }
                  }
                }}>
                  {row.attachInfo === "[]" ? "" : "查看"}
                </span>}
              </div>);
            }
          },
          {
            prop: "stautsName",
            label: "状态",
            align: "center",
            "min-width": "80px"
            // formatter: (row, column, cellValue, index) => {
            //   if (cellValue === 40) {
            //     return "已完成";
            //   }
            // }
          }
        ],
        tableAttr: {
          "max-height": "430px",
          height: "430px",
          border: true,
          fit: true,
          stripe: true,
          "show-header": true,
          "highlight-current-row": true,
          "cell-style": {
            "font-size": "16px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            border: "1px solid #ccc",
            "font-size": "16px"
          }
        },
        // 分页信息
        paginationAtrrs: {
          total: 0,
          "background": true,
          layout: "prev, pager, next",
          "current-page": 1,
          "page-size": 10
        }
      },
      fileListName: "",
      fileListName1: "",
      form: {},
      config: {},
      rules: [],
      pageNum: 1,
      pageSize: 10,
      // 年度演练计划弹窗
      dialogConfig: {
        title: "年度培训计划",
        isShow: false,
        type: "",
        btnList: [
          {
            name: "提交",
            type: "primary",
            id: "submit",
            size: "mini"
          },
          {
            name: "取消",
            id: "cancel",
            size: "mini"
          }
        ]
      },
      // 折叠面板
      titleConfig: [
        {
          title: "年度培训信息",
          name: "1",
          slot: "slot1"
        },
        {
          title: "填报信息",
          name: "2",
          slot: "slot2"
        }
      ],
      FilledBy: {},
      activeNames: ["1", "2"],
      yearsImportConfig: {
        table: {
          isSelectFlag: false,
          compRef: "yjrwlb",
          isSequenceFlag: true,
          isShowPage: false,
          resetFlag: true,
          loading: false,
          title: "",
          actions: [],
          tableData: [],
          columns: [
            {
              prop: "trainingProjectName",
              label: "培训项目",
              align: "left"
              // render: (h, { row }) => {
              //   return (<div>
              //     {<span style='color:#3561fd;cursor:pointer;text-decoration: underline;' {...{
              //       on: {
              //         click: () => {
              //           this.toTaskDetail(row.id);
              //         }
              //       }
              //     }}>
              //       {row.trainingProjectName}
              //     </span>}
              //   </div>);
              // }
            },
            {
              prop: "organisedUnitName",
              label: "主办单位",
              align: "left"
            },
            {
              prop: "trainingContent",
              label: "培训内容",
              align: "left",
              "min-width": "220px"
            },
            {
              prop: "trainingTarget",
              label: "培训对象",
              align: "center"
            },
            {
              prop: "trainingYearly",
              label: "培训年度",
              align: "center"
            },
            {
              prop: "trainingPeriod",
              label: "培训期次",
              align: "center",
              render: (h, { row }) => {
                return (
                  row.monthlyImportVoList.map((item, index) => {
                    // console.log(item,"????item",index);
                    if (row.monthlyImportVoList.length > 1 && index < row.monthlyImportVoList.length - 1) {
                      return (
                        <div style='border-bottom: 1px solid #EBEEF5;display:-webkit-box;height:48px;align-items:center;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp: 2;'>{`第${item.trainingPeriod}期`}</div>
                      );
                    } else {
                      return (
                        <div style='display:-webkit-box;height:48px;align-items:center;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp: 2;'>{`第${item.trainingPeriod}期`}</div>
                      );
                    }
                  })
                );
              }
            },
            {
              prop: "planCompleteTime",
              label: "完成时间",
              align: "center",
              render: (h, { row }) => {
                return (
                  row.monthlyImportVoList.map((item, index) => {
                    // console.log(item,"????item",index);
                    if (row.monthlyImportVoList.length > 1 && index < row.monthlyImportVoList.length - 1) {
                      return (
                        <div style='border-bottom: 1px solid #EBEEF5;display:-webkit-box;height:48px;align-items:center;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp: 2;'>{item.planCompleteTime}</div>
                      );
                    } else {
                      return (
                        <div style='display:-webkit-box;height:48px;align-items:center;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp: 2;'>{item.planCompleteTime}</div>
                      );
                    }

                  })
                );
              }
            }
          ],
          tableAttr: {
            "max-height": "300px",
            height: "300px",
            stripe: false,
            border: true,
            fit: true,
            "show-header": true,
            "highlight-current-row": true,
            "cell-style": {
              "font-size": "16px"
            },
            "header-cell-style": {
              "text-align": "center",
              "background-color": "#B1C8F9",
              border: "1px solid #ccc",
              color: "#333333",
              "font-size": "18px"
            }
          },
          // 分页信息
          paginationAtrrs: {
            total: 0,
            "background": true,
            layout: "prev, pager, next",
            "current-page": 1,
            "page-size": 10
          }
        },
        formConfig: {
          formData: [
            {
              type: "upload",
              label: "年度培训计划",
              prop: "ztqks",
              slot: "upload",
              action: "#",
              accept: "*",
              class: "sjgy",
              customize: true,
              tip: "仅支持xls文件，且不超过50mb",
              limit: 1,
              lableWidth: "130px"
            }
          ]
          // rules: {
          //   ztqks: [
          //     { required: true }
          //   ]
          // }
        },
        formConfig1: {
          formData: [
            {
              type: "input",
              label: "填报人",
              prop: "creator",
              class: "third",
              lableWidth: "140px",
              isDisabled: true
            },
            {
              type: "input",
              label: "单位及部门",
              prop: "unitDeptName",
              class: "third",
              lableWidth: "140px",
              isDisabled: true
            },
            {
              type: "dataPicker",
              label: "填报时间",
              prop: "createTime",
              class: "third",
              lableWidth: "140px",
              dateType: "datetime",
              isDisabled: true
            }
          ]
        },
        formConfig2: {
          formData: [
            {
              type: "upload",
              label: "附件",
              accept: "*",
              prop: "ztqks",
              slot: "upload1",
              action: "#",
              class: "sjgy",
              customize: true,
              tip: "支持jpg/png/pdf/doc等文件，且不超过50mb",
              limit: 1,
              lableWidth: "130px"
            }
          ]
          // rules: {
          //   ztqks: [
          //     { required: true }
          //   ]
          // }
        }
      },
      file: {},
      orgId: ""
    };
  },
  mounted() {
    this.list();
    this.getUnitTree();
    const FilledBy = {
      creator: JSON.parse(sessionStorage.getItem("account")).realName,
      creatorId: JSON.parse(sessionStorage.getItem("account")).id,
      deptId: JSON.parse(sessionStorage.getItem("org")).orgCode,
      unitDeptName: sessionStorage.getItem("dwbmName"),
      createTime: showTime(new Date())
    };
    this.FilledBy = FilledBy;
  },
  methods: {
    clear(val) {
      if (val === 1) {
        this.$refs.formComponent.fileList = [];
        this.yearsImportConfig.table.tableData = [];
        this.fileListName = "";
        this.$refs.formComponent.form = this.$refs.formComponent.$options.data().form;
        this.$nextTick(() => {
          this.$refs.formComponent.$refs.formInlines.clearValidate();
        });
      } else if (val === 2) {
        this.$refs.formComponent2.fileList = [];
        this.fileListName1 = "";
      }
    },
    // 下载模板
    onExport() {
      trainingYearDowmload().then(res => {
        common.downloadByBlob(res, `培训计划模板${new Date().getTime()}.xlsx`);
      });
    },
    // 抛出列表按钮
    onActionClick(item, index) {
      this[item.id](); // 调用按钮对应方法
    },
    cancel() {
      this.Quxiao();
    },
    // 弹窗按钮点击事件 对应id绑定事件
    async handleBtn(item) {
      this[item.id]();
    },
    Quxiao() {
      this.fileListName = "";
      this.fileListName1 = "";
      this.$refs.formComponent.fileList = [];
      this.$refs.formComponent2.fileList = [];
      this.yearsImportConfig.table.tableData = [];
      this.$refs.formComponent.form = this.$refs.formComponent.$options.data().form;
      this.$nextTick(() => {
        this.$refs.formComponent.$refs.formInlines.clearValidate();
      });
      this.dialogConfig.isShow = false;
      this.list();
    },
    // 弹窗关闭图标
    close() {
      this.Quxiao();
    },
    // 上传附件
    handleBeforeUploads(file) {
      const parmas = {
        file: file,
        directoryId: 0,
        isNew: false,
        moduleName: "plan_training"
      };
      UploadFile(this.common.convertFormData(parmas)).then(data => {
        this.$nextTick(() => {
          this.fileListName1 = file.name;
          this.$refs.formComponent2.fileList.push({ name: data.fileName, attachId: data.id });
        });
      });
    },
    // 导入
    YearlyUpload() {
      this.dialogConfig.isShow = true;
      this.$nextTick(() => {
        this.$refs.formComponent1.form = this.FilledBy;
      });
    },
    // 导入模板
    handleBeforeUpload(file, val) {
      this.file = file;
      trainingYearlyExcelDetail(this.common.convertFormData({ file: file })).then(res => {
        this.yearsImportConfig.table.tableData = res;
      });
      this.$nextTick(() => {
        console.log(this.$refs.formComponent.form, "this.$refs.formComponent.form");
        this.$refs.formComponent.form.ztqks = file.name;
        this.fileListName = file.name;
      });
    },
    // 查看
    async toTaskDetails(id) {
      const res = await trainingYearlyDetail({ id: id });
      const attachInfo = JSON.parse(res.attachInfo);
      // console.log(attachInfo, "attachInfo");
      // loadFile({ id: attachInfo[0].attachId }).then(data => {
      //   window.open(data);
      // });
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.6)"
      });
      loadFile({ id: attachInfo[0].attachId }).then(res => {
        const a = document.createElement("a");
        const objectUrl = URL.createObjectURL(res);
        a.setAttribute("href", objectUrl);
        a.setAttribute("download", attachInfo[0].attachName);
        a.click();
        loading.close();
      }).catch(() => {
        loading.close();
      });
    },
    // 提交
    submit() {
      if (this.fileListName === "") {
        this.$message({
          message: "请导入年度培训计划模板",
          type: "warning"
        });
      } else {
        const list = this.$refs.formComponent2.fileList;
        const attachInfo = [];
        list.forEach(item => {
          attachInfo.push(
            {
              attachName: item.name,
              attachId: item.attachId
            }
          );
        });
        const parmas = {
          attachInfo: JSON.stringify(attachInfo),
          trainingYearlyImport: this.yearsImportConfig.table.tableData
        };
        trainingYearlyUpload(parmas).then(data => {
          this.$message({
            message: "提交成功",
            type: "success"
          });
          this.list();
          this.dialogConfig.isShow = false;
        });
      }

    },
    // 检索
    async query() {
      const parmas = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        trainingProjectName: this.form.trainingProjectName,
        trainingContent: this.form.trainingContent,
        trainingTarget: this.form.trainingTarget,
        trainingYearly: this.form.trainingYearly,
        stauts: this.form.stauts,
        planCompleteTime: this.form.planCompleteTime ? this.form.planCompleteTime.slice(0, 7) : "",
        organisedUnitId: this.orgId
      };
      const res = await trainingYearlyListPage(parmas);
      this.table.tableData = res.data;
      this.table.paginationAtrrs.total = res.total;
    },
    // 重置
    reset() {
      this.form = this.$options.data().form;
      this.$refs.yjrwlb.paginationAtrrsInner["current-page"] = 1;
      this.list();
    },
    // 列表
    async list() {
      const parmas = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      const res = await trainingYearlyListPage(parmas);
      this.table.tableData = res.data;
      this.table.paginationAtrrs.total = res.total;
    },
    // 列表表格按钮事件
    actionHandle(item, scope) {
      if (item === "编辑") {
        this.HanEdit(scope.row);
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageNum = val["current-page"];
      this.pageSize = val["page-size"];
      this.list();
    },
    // 树状接口
    getUnitTree() {
      getUnitTreeApi().then(res => {
        this.formData[0].treeData.attrs.data = res;
      });
    },
    // 树状选择
    deptChoose(val, item) {
      this.$set(this.form, "organisedUnitId", val[0].orgName);
      this.orgId = val[0].id;
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../../assets/style/common.less";
@import "../../../assets/style/ComponentStyle.less";
@import "../../../assets/style/pop-upNotification.less";

:deep(.el-breadcrumb__inner.is-link) {
  font-weight: 100;
  color: #fff;
}

.EmergencyList :deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #3270ff;
}

.box {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 15px;
  background-color: #fff;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
}

.yqwcsj {
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__inner) {
    width: auto;
  }
}

.yuandian1 {
  display: inline-block;
  background-color: #ccc;
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.upload {
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.el-input__inner) {
    width: 98%;
    color: rgb(10, 99, 241);
    text-decoration: underline;
  }

  :deep(.el-button) {
    padding: 9px 15px !important;
  }
}

:deep(.el-upload) {
  width: 100% !important;
}

.ydBgcolor {
  background-color: #246dfd;
  box-shadow: 0px 0px 8px 0px rgb(10, 99, 241);
}

:deep(.el-step__icon.is-text) {
  border: none;
}

:deep(.el-step__title.is-process) {
  font-weight: normal;
}

.uploadBox {
  :deep(.el-upload-list) {
    display: none;
  }
}
</style>
